import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/anime_provider.dart';
import '../widgets/favorite_button.dart';
import '../../core/utils/chinese_title_mapper.dart';
import '../../domain/entities/anime.dart';

/// 排行榜页面
class RankingPage extends StatefulWidget {
  const RankingPage({super.key});

  @override
  State<RankingPage> createState() => _RankingPageState();
}

class _RankingPageState extends State<RankingPage> with TickerProviderStateMixin {
  late TabController _tabController;
  late ScrollController _scrollController;
  int _currentTabIndex = 0;

  // 排行榜类型配置
  final List<Map<String, dynamic>> _rankingTypes = [
    {
      'title': '评分排行',
      'icon': Icons.star,
      'color': Colors.amber,
      'subtitle': '最高评分动漫',
    },
    {
      'title': '人气排行',
      'icon': Icons.trending_up,
      'color': Colors.orange,
      'subtitle': '最受欢迎动漫',
    },
    {
      'title': '当前播放',
      'icon': Icons.play_circle,
      'color': Colors.blue,
      'subtitle': '正在播放动漫',
    },
    {
      'title': '喜爱排行',
      'icon': Icons.favorite,
      'color': Colors.red,
      'subtitle': '最受喜爱动漫',
    },
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _rankingTypes.length, vsync: this);
    _scrollController = ScrollController();
    
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        setState(() {
          _currentTabIndex = _tabController.index;
        });
        // 切换标签时懒加载对应数据
        _loadTabData(_tabController.index);
      }
    });

    // 添加滚动监听
    _scrollController.addListener(_onScroll);

    // 初始化时只加载第一个标签的数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadTabData(0); // 只加载评分排行榜
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  /// 滚动监听，检测是否到达底部
  void _onScroll() {
    if (_scrollController.position.pixels >= 
        _scrollController.position.maxScrollExtent - 200) {
      // 距离底部200px时开始加载更多
      _loadMoreData();
    }
  }

  /// 懒加载指定标签的数据
  void _loadTabData(int tabIndex) {
    final provider = context.read<AnimeProvider>();
    
    switch (tabIndex) {
      case 0: // 评分排行
        if (provider.rankingByScore.isEmpty) {
          provider.fetchRankingByScore();
        }
        break;
      case 1: // 人气排行
        if (provider.rankingByPopularity.isEmpty) {
          provider.fetchRankingByPopularity();
        }
        break;
      case 2: // 当前播放
        if (provider.rankingByMembers.isEmpty) {
          provider.fetchRankingByMembers();
        }
        break;
      case 3: // 喜爱排行
        if (provider.rankingByFavorites.isEmpty) {
          provider.fetchRankingByFavorites();
        }
        break;
    }
  }

  /// 根据当前选项卡加载更多数据
  void _loadMoreData() {
    final provider = context.read<AnimeProvider>();
    if (provider.isLoadingMore) return;

    switch (_currentTabIndex) {
      case 0: // 评分排行
        provider.loadMoreRankingByScore();
        break;
      case 1: // 人气排行
        provider.loadMoreRankingByPopularity();
        break;
      case 2: // 当前播放
        provider.loadMoreRankingByMembers();
        break;
      case 3: // 喜爱排行
        provider.loadMoreRankingByFavorites();
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text(
          '动漫排行榜',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: Colors.white,
        elevation: 0,
        scrolledUnderElevation: 1,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              context.read<AnimeProvider>().fetchAllRankings(refresh: true);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('正在刷新排行榜数据...'),
                  duration: Duration(seconds: 2),
                ),
              );
            },
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          isScrollable: true,
          tabAlignment: TabAlignment.start,
          labelColor: Theme.of(context).primaryColor,
          unselectedLabelColor: Colors.grey,
          indicatorColor: Theme.of(context).primaryColor,
          indicatorWeight: 3,
          tabs: _rankingTypes.map((type) => Tab(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  type['icon'] as IconData,
                  size: 18,
                  color: _currentTabIndex == _rankingTypes.indexOf(type)
                      ? type['color'] as Color
                      : Colors.grey,
                ),
                const SizedBox(width: 6),
                Text(type['title'] as String),
              ],
            ),
          )).toList(),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildRankingList('score'),
          _buildRankingList('popularity'),
          _buildRankingList('airing'),
          _buildRankingList('favorites'),
        ],
      ),
    );
  }

  /// 构建排行榜列表
  Widget _buildRankingList(String type) {
    return Consumer<AnimeProvider>(
      builder: (context, provider, child) {
        List<Anime> animeList;
        String emptyMessage;
        bool isCurrentTab = false;
        
        switch (type) {
          case 'score':
            animeList = provider.rankingByScore;
            emptyMessage = '暂无评分排行数据';
            isCurrentTab = _currentTabIndex == 0;
            break;
          case 'popularity':
            animeList = provider.rankingByPopularity;
            emptyMessage = '暂无人气排行数据';
            isCurrentTab = _currentTabIndex == 1;
            break;
          case 'airing':
            animeList = provider.rankingByMembers;
            emptyMessage = '暂无当前播放数据';
            isCurrentTab = _currentTabIndex == 2;
            break;
          case 'favorites':
            animeList = provider.rankingByFavorites;
            emptyMessage = '暂无喜爱排行数据';
            isCurrentTab = _currentTabIndex == 3;
            break;
          default:
            animeList = [];
            emptyMessage = '暂无数据';
        }

        // 显示加载状态：当前标签页且数据为空时
        if (animeList.isEmpty && isCurrentTab) {
          if (provider.isLoading) {
            return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                  SizedBox(
                    width: 50,
                    height: 50,
                    child: CircularProgressIndicator(
                      strokeWidth: 3,
                      valueColor: AlwaysStoppedAnimation<Color>(
                        Theme.of(context).primaryColor,
                      ),
                    ),
                  ),
                  const SizedBox(height: 20),
                  Text(
                    '正在加载排行榜数据...',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey[600],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '首次加载可能需要几秒钟',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[500],
                    ),
                  ),
              ],
            ),
          );
          }
        }

        if (provider.hasError && animeList.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.error_outline,
                  size: 64,
                  color: Colors.grey[400],
                ),
                const SizedBox(height: 16),
                Text(
                  provider.errorMessage,
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 16,
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () {
                    provider.fetchAllRankings(refresh: true);
                  },
                  child: const Text('重试'),
                ),
              ],
            ),
          );
        }

        if (animeList.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.inbox_outlined,
                  size: 64,
                  color: Colors.grey[400],
                ),
                const SizedBox(height: 16),
                Text(
                  emptyMessage,
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 16,
                  ),
                ),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: () => provider.fetchAllRankings(refresh: true),
          child: ListView.builder(
            controller: _scrollController,
            padding: const EdgeInsets.all(16),
            itemCount: animeList.length + (provider.isLoadingMore ? 1 : 0), // 加载更多时+1
            itemBuilder: (context, index) {
              if (index < animeList.length) {
                final anime = animeList[index];
                return _buildRankingCard(anime, index + 1, type);
              } else {
                // 加载更多指示器
                return _buildLoadMoreIndicator();
              }
            },
          ),
        );
      },
    );
  }

  /// 构建排行榜卡片
  Widget _buildRankingCard(Anime anime, int rank, String type) {
    final chineseTitle = ChineseTitleMapper.getBestChineseTitle(
      title: anime.title,
      titleJapanese: anime.titleJapanese,
      titleEnglish: anime.titleEnglish,
      titleSynonyms: anime.titleSynonyms,
    );

    final rankingConfig = _rankingTypes[_currentTabIndex];
    final Color rankColor = rank <= 3 
        ? (rank == 1 ? Colors.amber : rank == 2 ? Colors.grey[400]! : Colors.brown[300]!)
        : rankingConfig['color'] as Color;

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      child: Card(
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: () {
            Navigator.pushNamed(
              context,
              '/detail',
              arguments: {'id': anime.id},
            );
          },
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                // 排名徽章
                Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: rankColor,
                    borderRadius: BorderRadius.circular(20),
                    boxShadow: [
                      BoxShadow(
                        color: rankColor.withValues(alpha: 0.3),
                        blurRadius: 4,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Center(
                    child: rank <= 3
                        ? Icon(
                            rank == 1 ? Icons.looks_one : rank == 2 ? Icons.looks_two : Icons.looks_3,
                            color: Colors.white,
                            size: 24,
                          )
                        : Text(
                            '$rank',
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                  ),
                ),
                const SizedBox(width: 16),
                
                // 动漫封面
                ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: SizedBox(
                    width: 60,
                    height: 85,
                    child: anime.imageUrl.isNotEmpty
                        ? Image.network(
                            anime.imageUrl,
                            fit: BoxFit.cover,
                            errorBuilder: (context, error, stackTrace) {
                              return Container(
                                color: Colors.grey[300],
                                child: const Icon(Icons.image_not_supported, size: 24),
                              );
                            },
                          )
                        : Container(
                            color: Colors.grey[300],
                            child: const Icon(Icons.image, size: 24),
                          ),
                  ),
                ),
                const SizedBox(width: 16),
                
                // 动漫信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        chineseTitle,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFF2C3E50),
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 8),
                      
                      // 显示不同类型的统计信息
                      _buildStatInfo(anime, type),
                      
                      const SizedBox(height: 8),
                      
                      // 年份和状态
                      Row(
                        children: [
                          if (anime.year != null) ...[
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                              decoration: BoxDecoration(
                                color: Colors.blue[50],
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Text(
                                '${anime.year}年',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.blue[700],
                                ),
                              ),
                            ),
                            const SizedBox(width: 6),
                          ],
                          if (anime.status.isNotEmpty)
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                              decoration: BoxDecoration(
                                color: _getStatusColor(anime.status),
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Text(
                                _getStatusText(anime.status),
                                style: const TextStyle(
                                  fontSize: 12,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                        ],
                      ),
                    ],
                  ),
                ),
                
                // 收藏按钮
                FavoriteButton(
                  anime: anime,
                  onFavoriteChanged: () {
                    // 收藏状态变化后的处理
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建统计信息显示
  Widget _buildStatInfo(Anime anime, String type) {
    switch (type) {
      case 'score':
        return Row(
          children: [
            Icon(Icons.star, color: Colors.amber, size: 16),
            const SizedBox(width: 4),
            Text(
              '评分: ${anime.score > 0 ? anime.score.toStringAsFixed(1) : '暂无'}',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[700],
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        );
      case 'popularity':
        return Row(
          children: [
            Icon(Icons.trending_up, color: Colors.orange, size: 16),
            const SizedBox(width: 4),
            Text(
              '收藏: ${(anime.members ?? 0) > 0 ? _formatNumber(anime.members ?? 0) : '暂无'}',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[700],
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        );
      case 'airing':
        return Row(
          children: [
            Icon(Icons.play_circle, color: Colors.blue, size: 16),
            const SizedBox(width: 4),
            Text(
              '状态: ${_getStatusText(anime.status)}',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[700],
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        );
      case 'favorites':
        return Row(
          children: [
            Icon(Icons.favorite, color: Colors.red, size: 16),
            const SizedBox(width: 4),
            Text(
              '喜爱: ${(anime.favorites ?? 0) > 0 ? _formatNumber(anime.favorites ?? 0) : '暂无'}',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[700],
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        );
      default:
        return const SizedBox.shrink();
    }
  }

  /// 格式化数字显示
  String _formatNumber(int number) {
    if (number >= 1000000) {
      return '${(number / 1000000).toStringAsFixed(1)}M';
    } else if (number >= 1000) {
      return '${(number / 1000).toStringAsFixed(1)}K';
    } else {
      return number.toString();
    }
  }

  /// 获取状态颜色
  Color _getStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'finished airing':
      case 'completed':
        return Colors.green;
      case 'currently airing':
      case 'airing':
        return Colors.blue;
      case 'not yet aired':
      case 'upcoming':
        return Colors.orange;
      default:
        return Colors.grey;
    }
  }

  /// 获取状态文本
  String _getStatusText(String status) {
    switch (status.toLowerCase()) {
      case 'finished airing':
      case 'completed':
        return '已完结';
      case 'currently airing':
      case 'airing':
        return '连载中';
      case 'not yet aired':
      case 'upcoming':
        return '即将播出';
      default:
        return '未知';
    }
  }

  /// 构建加载更多指示器
  Widget _buildLoadMoreIndicator() {
    return Container(
      padding: const EdgeInsets.all(20),
      child: const Center(
        child: Column(
          children: [
            SizedBox(
              width: 24,
              height: 24,
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
            SizedBox(height: 8),
            Text(
              '加载更多中...',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      ),
    );
  }
} 